﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using ICSharpCode.SharpZipLib.Zip;
using static bmapi.Models.ShowModel;

namespace bmapi.Controllers
{
    [Route("style")]
    public class StyleController : PageController
    {
        #region 款式查询
        //款式查询    
        [HttpGet]
        public HttpResponseMessage SelectStyle(int page = 1, int limit = 15, string ModelName = null, string brand = null, string type = null, DateTime? sTime = null, DateTime? eTime = null)
        {
            int loginid = GetCrrentIDByToken();
            if (loginid == 0)
                return AssistFun.toJson(new { status = 201, tip = "工号不存在", data = "" });
            User user = GetUserByLoginID(loginid);

            string sql = "";
            if (ModelName != null)
            {
                sql = string.Format("and (Model_tb.name like '%{0}%' or Style_tb.name like '%{0}%') ", ModelName);
                sql += PingJieCmdForStyle(user.PLID, brand, type, sTime, eTime);
            }
            else
            {
                sql += PingJieCmdForStyle(user.PLID, brand, type, sTime, eTime);
            }
            int totalPage = 0;
            int totalRow = 0;
            string tables = "Style_tb join Model_tb on Style_tb.style_id=Model_tb.style_id";
            string fileds = "is_model as model,Style_tb.name as StyleName,Model_tb.name as ModelName,brand,type,time,state,Style_tb.style_id as StyleId,Style_tb.save_model as SaveModel,Model_tb.id as ModelId";
            try
            {
                //DataTable dt = SQLCommand.GetDataListByPage(tables, fileds, "Style_tb.style_id desc", sql, limit, page, out totalPage, out totalRow);
                DataTable dt = null;
                SQLCommand.GetDataListByPage(tables, fileds, "Style_tb.style_id desc", sql, limit, page, out totalPage, out totalRow,out dt);
                if (dt==null)
                    return AssistFun.toJson(new { status = 201, tip = "暂时没有款式信息", data = "" });
                List<StyleInfo> styleinfo = AssistFun.DataTableToList<StyleInfo>(dt);
                return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = totalRow, rows = styleinfo } });
                    
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new { status = 201, tip = e.Message, data = "" });
            }

        }
        private string PingJieCmdForStyle(int plid, string brand, string type, DateTime? sTime = null, DateTime? eTime = null)
        {
            string sql = "";
            //if (plid > 0)
            //    sql += " and Model_tb.PLID=" + plid;

            if (brand != null)
                sql += string.Format("and brand like '%{0}%'", brand);
            if (type != null )
                if(type.Replace(" ", "") != "全部")
                    sql += string.Format("and type like '%{0}%'", type);

            if (sTime != null)
            {
                if (SQLCommand.IsOracle)
                    sql += " and time>=to_date('" + sTime + "','yyyy/mm/dd hh24-mi-ss')";
                else
                    sql += "and time>=CONVERT(varchar(100), '" + sTime + "', 120)";
            }
            if (eTime != null)
            {
                if (SQLCommand.IsOracle)
                    sql += " and time<=to_date('" + eTime + "','yyyy/mm/dd hh24-mi-ss')";
                else
                    sql += "and time<=CONVERT(varchar(100), '" + eTime + "', 120)";
            }
                
            return sql;
        }
        #endregion    

        /// <summary>
        /// 款式文件打包下载 
        /// </summary>  
        /// <param name="stylename"></param>
        /// <returns></returns> 
        [HttpGet,Route("downStyle")]
        public HttpResponseMessage DownStyle(int ModelId,string token)
        {
            try
            {
                int loginid = GetCrrentIDByToken(token);
                if(loginid==0)
                    return AssistFun.toJson(new { status = 201, tip ="你无权下载" });
                string stylePath = GetStylePath(ModelId);
                int end = stylePath.LastIndexOf(@"\");
                string name = stylePath.Substring(end + 1);
                string TartgetFile = stylePath.Substring(0, end) + "\\" + name+".zip";

                using (ZipOutputStream ComStream = new ZipOutputStream(File.Create(TartgetFile)))
                {
                    ComStream.SetLevel(6);      //压缩等级
                    if (!Directory.Exists(stylePath))
                        return AssistFun.toJson(new { status = 201, tip = "不存在款式"+name+"的目录" });
                    //压缩文件 有同名压缩文件会自动替换                    
                    ZipFloder(stylePath, ComStream, stylePath);       
                }
                //成功压缩  下载文件 
                return Download(TartgetFile);
            }
            catch (Exception e)
            {
                if(e.Message.IndexOf("正由另一进程使用")>0)
                    return AssistFun.toJson(new { status = 201, tip = "文件正在被打包..." });
                return AssistFun.toJson(new { status = 201, tip = e.Message });
            }
        }
     

        /// <summary>
        /// 修改存储模式 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPut]
        public HttpResponseMessage UpdateStyle(dynamic obj)
        {
            if (obj == null)
                return AssistFun.toJson(new { status = 201, tip = "请提供修改数据" });
            else
            {
                #region  修改参数
                int styleid = Convert.ToInt32(obj.StyleId);
                string type = obj.Type.ToString();
                string ismodel = obj.model.ToString();
                string brand = obj.Brand.ToString();
                #endregion
                string sql = "update Style_tb set is_model=@isModel,brand=@brand,type=@type where style_id=@styleid";
                SQLCommand sc = new SQLCommand(sql);
                sc.Add("@isModel", ismodel);
                sc.Add("@brand", brand);
                sc.Add("@type", type);
                sc.Add("@styleid",styleid);
                int rtn = sc.ExecuteNonQuery();
                if(rtn==1)
                    return AssistFun.toJson(new { status = 200, tip = "成功" });
                else
                    return AssistFun.toJson(new { status = 201, tip = "失败" });
            }            

        }

        #region  图片上传 
        [HttpPost,Route("uploadimg")]
        public HttpResponseMessage UploaImg()
        {
            string path = "";
            int step = 0;
            try
            {
                HttpPostedFile file = HttpContext.Current.Request.Files["file"];
                HttpPostedFileBase uploadfile = new HttpPostedFileWrapper(file) as HttpPostedFileBase;
                if (uploadfile == null)
                {
                    return AssistFun.toJson(new { status = 201, tip = "no:请选择文件" });
                }
                if (uploadfile.FileName == "")
                {
                    return AssistFun.toJson(new { status = 201, tip = "no:请选择文件,fileup:" + file.FileName });
                }
                HttpContext context = HttpContext.Current;
                string name = context.Request.Params["ModelName"];
                int id = Convert.ToInt32(context.Request.Params["ModelId"]);
                string fileExt = Path.GetExtension(uploadfile.FileName);
                string dir = GetStylePath(id) + "\\A3\\" + name + fileExt;
                dir = dir.ToLower();
                string rootPath = HttpContext.Current.Server.MapPath("/");
                string readDir = Path.GetDirectoryName(dir);
                if (!Directory.Exists(readDir))
                    Directory.CreateDirectory(readDir);

                step = 1;                
                uploadfile.SaveAs(dir);
                //图片成功上传  存入数据库 (先进行数据添加)  
                UpdateModel(id, dir.Remove(0, dir.LastIndexOf("BuyiRoot".ToLower())), ref step);

                return AssistFun.toJson(new { status = 200, tip = "成功 step:"+step });
            }
            catch (Exception ex)
            {
                return AssistFun.toJson(new { status = 201, tip = "no:" + ex.Message + "dir: "+path+ " step:" + step });
            }
        }

        private HttpResponseMessage UpdateModel(int ModelId,string dir,ref int step)
        {
            try
            {
                step =2;
                //上传成功 将图片存到数据库中
                string sql = "update Model_tb set image=@image where id=@modelid";
                step = 3;
                SQLCommand sc = new SQLCommand(sql);
                sc.Add("@image", dir);
                sc.Add("@modelid", ModelId);
                step = 4;
                if (sc.ExecuteNonQuery() <= 0)
                {
                    step = 11;
                    return AssistFun.toJson(new { status = 201, tip = "图片成功上传，信息录入失败" });
                }
                else
                {
                    step = 5;
                    return AssistFun.toJson(new { status = 200, tip = "图片成功上传" });
                }
            }
            catch (Exception ex)
            {
                step = 6;
                return AssistFun.toJson(new { status = 201, tip = ex.Message });
            }
           

        }

        #endregion

        /// <summary>
        /// 删除款式 暂时不做样式的删除 前提  没有相应的订单
        /// </summary> 
        /// <param name="StyleId"></param>
        [HttpDelete]
        public HttpResponseMessage DeleteStyle(int StyleId)
        {
            try
            {
                SQLCommand sc = null;
                //删除数据导入时产生的Task_tb记录
                string sql = "delete from Task_tb where id in(select id from Model_tb where style_id=@styleid) and code=1";
                sc = new SQLCommand(sql, "@styleid", StyleId);
                List<SQLCommand> cmds = new List<SQLCommand>() {sc};

                sql = "select o_model_id from Order_tb where o_model_id in(select id from Model_tb join Style_tb on Model_tb.style_id=Style_tb.style_id where Style_tb.style_id=@styleid)";
                sc = new SQLCommand(sql, "@styleid", StyleId);
                DataTable dt = sc.ExecuteScalars();
                if(dt!=null)
                    return AssistFun.toJson(new { status = 201, tip = "该款已被使用禁止删除" });
                sql = "select style_time,name from Style_tb where style_id=@styleid";
                sc = new SQLCommand(sql, "@styleid", StyleId);
                DataRow dr = sc.ExecuteOneRow();
                if(dr == null)
                    return AssistFun.toJson(new { status = 201, tip = "数据库中不存在该款式信息" });
                sql = "delete from Style_tb where style_id=@styleid";
                sc = new SQLCommand(sql, "@styleid", StyleId);
                cmds.Add(sc);
                int res = SQLCommand.ExecTran(cmds);
                if (res == 0)
                    return AssistFun.toJson(new { status = 201, tip = "操作失败" });
                else
                {
                    //删除款式文件  
                    string path = m_buyiRoot + "\\buyistyle\\" + dr["style_time"].ToString() + "\\" + dr["name"].ToString();
                    if(Directory.Exists(path))
                        DeleteFolder(path);
                }
                    return AssistFun.toJson(new { status = 200, tip = "成功" });
            }
            catch (Exception ex)
            {
                WriteDebug("DeleteStyle 异常 :",ex.Message);
                return AssistFun.toJson(new { status = 201, tip = "异常，操作失败" });
            }            
        }
    }
}
